<template>
  <el-row v-if="!loading&&firstIn" class="business-tab">
    <el-collapse v-model="activeName" accordion class="collapse" @change="collapseChange">
      <el-collapse-item :title="$t('webchat.relationBusiness')" name="1">
         <history-table
            :titleName ="$t('webchat.relationBusiness')"
            :cid="cid"
            v-if="toggleHistory && activeName === '1'"
            :businessNumbers="newBusinessNumbers"
            :type="'related'"
            :cacheId="cacheId"
            :callScreen="callScreen"
            @backHistory="toggleFun"
          ></history-table>
      </el-collapse-item>
      <el-collapse-item :title="$t('business.businessHistory')" name="2">
          <history-table
            :titleName ="$t('business.businessHistory')"
            v-if="toggleHistory && activeName === '2'"
            :cid="cid"
            :callScreen="callScreen"
            @backHistory="toggleFun"
          ></history-table>
      </el-collapse-item>
      <el-collapse-item class="no-padding" :title="$t('business.newBusiness')" name="3">
        <new-business
          ref="newBusiness"
          v-show="!toggleHistory && item.newBusiness"
          v-if="custInfo && custInfo._id"
          :cid="cid"
          :cdrCall="cdrCall"
          :callId="callId"
          :custInfo="custInfo"
          v-on:event="businessEvent"
          :cacheId="cacheId"
        ></new-business>
        <temporary-business v-show="!toggleHistory" v-if="item.isStartStep === true" :cacheId="cacheId" :detail="item" v-on:event="businessEvent"
        :relatedBusinessShow="relatedBusinessShow"></temporary-business>
        <business-info v-show="!toggleHistory" v-if="item.isStartStep === false" :detail="item" :cacheId="cacheId" v-on:event="businessEvent" :callScreen="callScreen" :fixed="fixed" :showHistory="showHistory"
        :relatedBusinessShow="relatedBusinessShow"></business-info>
      </el-collapse-item>
    </el-collapse>
  </el-row>
</template>
<script>
  import BusinessInfo from './BusinessInfoWebchat.vue'
  import NewBusiness from './NewBusinessWebchat.vue'
  import TemporaryBusiness from './TemporaryBusinessWebchat.vue'
  // import {getCache} from '@/utils/m7Utils.js'
  export default {
    name: 'BusinessSum',
    data () {
      return {
        loading: true,
        firstIn: false,
        toggleHistory: false,
        activeName:'3',
        newBusinessNumbers: []
      }
    },
    props: {
      busId: String,
      refresh: String,
      cid: String, // 客戶id
      custInfo: {type: Object, default: function () { return {} }},
      showHistory: {type: Boolean, default: false},
      showHistoryTable: {type: Boolean, default: false},
      link: {type: String, default: ''},
      cacheId: {type: String, default: ''}, // 缓存工单信息的id
      cdrCall: {type: Boolean, default: false},
      callId: String,
      callScreen: {type: Boolean, default: false}, // 工单组件在dialog中则传true
      reload: {type: Number, default: 0},
      fixed: {type: String, default: ''}, // 工单吸顶
      relatedBusinessShow: {type: Boolean, default: true},//详情中不能再点击详情
      businessNumbers: {type: Array, default: ()=>[]}
    },
    provide: function () {
      return {
        link: this.link
      }
    },
    components: {
      BusinessInfo,
      NewBusiness,
      TemporaryBusiness
    },
    computed: {
      item () {
        let item
        let busId = this.busId
        if (busId) {
          item = this.$store.state.business['current'].businessAction[this.busId]
        } else {
          item = {newBusiness: true}
        }
        return item
      }
    },
    methods: {
      collapseChange(val){
        if(val == 2 || val == 1){
          this.toggleFun(true)
        } else{
          this.toggleFun(false)
        }
      },
      toggleFun (type) {
        this.toggleHistory = type
        if (type) {
          this.$store.commit('business/REFRESH_CUSTOMER_BUSINESS_HISTORY', this.cid)
        }
      },
      businessEvent (eventData) {
        let eventType = eventData.event
        let data = eventData.data  
        if(data.form){           
            data.form.existAttach = false
            for(var key in data.form){
              if(data.form[key] instanceof Array){
                if(data.form[key].length>0&&data.form[key][0].name){
                  data.form.existAttach = true
                }
              }
            }
            for(var key in data.form.actionFields){
              if(data.form.actionFields[key] instanceof Array){
                if(data.form.actionFields[key].length>0&&data.form.actionFields[key][0].name){
                  data.form.existAttach = true
                }
              }
            }
        }
        if (eventType === 'addBusinessTask') {
          if(this.callScreen){
            data.form.createMode = 'call'
          }else{
            data.form.createMode = this.$route.path.split('/')[2]
          }
          let id = this.$route.path.split('/')[4]
          if (this.link === 'call') {
            data.form.callId = id
          } else if (this.link === 'webchat') {
            data.form.linkWebchat = id
          } else if (this.link === 'mail') {
            data.form.linkMail = id
          }
          this.$store.dispatch('addBusinessTask', data.form).then((res) => {
            eventData.data._id = res
            this.$emit('event', eventData)
            // 工单新建成功，删除该缓存
            if (data.form._id === undefined) {
              // id为undefined时新建工单组件冒出的事件
              this.$store.commit('business/DELETE_BUS_CACHE', this.cacheId)
              this.$store.commit('business/DELETE_BUS_CACHE', this.cacheId + 'nextAction')
            }
            this.getInfoData()
          })
        } else if (eventType === 'addTempBusinessTask') {
          if(this.callScreen){
            data.form.createMode = 'call'
          }else{
            data.form.createMode = this.$route.path.split('/')[2]
          }
          let stepCache = {}
          stepCache._id = data.stepCacheCurId ? data.stepCacheCurId : ''
          stepCache.actionId = data.form.nextAction
          let actionFields = data.form.actionFields ? data.form.actionFields : null
          let id = this.$route.path.split('/')[4]
          if (this.link === 'webchat') {
            data.form.linkWebchat = id
          }
          data.form.stepCache = Object.assign(stepCache, actionFields)
          this.$store.dispatch('addTempBusinessTask', data.form).then((res) => {
            eventData.data._id = res
            this.$message.success(this.$t('business.businessTempSuccess'))
            this.$emit('event', eventData)
            // 工单暂存成功，删除该缓存
            if (data.form._id === undefined) {
              // id为undefined时新建工单组件冒出的事件
              this.$store.commit('business/DELETE_BUS_CACHE', this.cacheId)
              this.$store.commit('business/DELETE_BUS_CACHE', this.cacheId + 'nextAction')
            }
          })
        } else if (eventType === 'stepAction') {
          this.$store.dispatch('excuteBusinessStepAction', data.form).then((res) => {
            this.$emit('event', eventData)
            this.$store.commit('business/DELETE_BUS_CACHE', this.item._id + 'action')
          })
        } else if (eventType === 'stepActionTemp') {
          if(data.dataForm){
            data.dataForm.existAttach = false
            for(var key in data.dataForm){
              if(data.dataForm[key] instanceof Array){
                if(data.dataForm[key].length>0&&data.dataForm[key][0].name){
                  data.dataForm.existAttach = true
                }
              }
            }
          }
          this.$store.dispatch('saveTempStepInfo', data.dataForm).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('business.businessTempSuccess'))
            } else {
              this.$message.error(res.message)
            }
            this.$emit('event', eventData)
          })
        } else if (eventType === 'commentAction') {
        } else if (eventType === 'backAction') {
          this.$store.dispatch('excuteBusinessBackAction', data.form).then(() => {
            this.$emit('event', eventData)
            this.$store.commit('business/DELETE_BUS_CACHE', this.item._id + 'back')
          })
        } else if (eventType === 'changeBusinessMaster') {
          this.$emit('event', eventData)
        }
      },
      init () {
        this.$nextTick(() => {
          let newBusiness = this.$refs.newBusiness
          if (newBusiness) {
            let busCache = this.$getCache('busCache') || {}
            let flow = busCache[this.cacheId] && busCache[this.cacheId].flow || ''
            newBusiness.refreshForm(flow)
          } 
          this.getInfoData()
          this.toggleHistory = false
        })
      },
      fetchData () {
        let self = this
        if (this.refresh === 'business' || !this.refresh) {
          this.firstIn = true
        }
        Promise.all([
          this.$store.dispatch('getCache', {type: 'businessFlowStep'}),
          this.$store.dispatch('getCache', {type: 'businessFlow'}),
          this.$store.dispatch('getCache', {type: 'agents'}),
          this.$store.dispatch('getCache', {type: 'custTmpls'})
        ]).then(() => {
          self.loading = false
        })
      },
      // 获取在线实时数据
      getInfoData(){
        if (this.cacheId) {
          this.$store.dispatch('queryChatInfoById', {_id: this.cacheId}).then((res) => {
            console.log(res,'res')
            if(res && res.success && res.chatSession && res.chatSession.businessNumbers.length>0) {
              this.newBusinessNumbers = res.chatSession.businessNumbers
            } else {
              this.newBusinessNumbers = []
            }
          })
        }
      }
    },
    watch: {
      // 工单组件首次加载
      refresh () {
        if (this.refresh === 'business' || !this.refresh) {
          this.firstIn = true
        }
      },
      // 切换card重新加载
      reload (cur, old) {
        this.activeName = '3'
        this.init()
      },
      item () {
        // item变化且为新建工单时，
        if (this.item.newBusiness) {
          this.init()
        }
      },
      businessNumbers () {
        this.newBusinessNumbers = this.businessNumbers
      }
    },
    beforeCreate: function () {
      this.$options.components.HistoryTable = require('./HistoryTableWebchat.vue').default
    },
    beforeMount () {
      this.fetchData()
    }
  }
</script>
<style lang="stylus">
  @import '../../../../../assets/common.styl'
  .no-padding .el-collapse-item__content
    padding  0
  .at-text
    color $c-pink
  .collapse
    .el-collapse-item__header
      font-size 12px !important
      padding 0 10px
</style>
<style lang="stylus" scoped>
  @import '../../../../../assets/common.styl'
  .business-tab
    // padding 0 10px
    overflow-x hidden
  .el-row
    font-size 14px
    line-height 18px
    .add-ramark
      font-size 16px
      line-height 20px
      margin-left 26px
      span
        height 20px
        line-height 20px
      i
        display inline-block
        width 20px
        height 20px
        background-color  $c-main
        margin-right 8px
</style>
